from flask import jsonify, request
from app.libs.helper import is_isbn_or_key
from app.spider.yuishu_book import YuShuBook
from app.forms.book import SearchForm
from . import web
import json
from app.view_models.book import BookCollection


@web.route('/book/search')
def search():
    """
    search的视图函数
    :return:
    """
    search_form = SearchForm(request.args)
    books = BookCollection()
    if search_form.validate():
        q = search_form.q.data.strip()
        page = search_form.page.data
        isbn_or_key = is_isbn_or_key(q)
        yu_shu_book = YuShuBook()
        if isbn_or_key == 'isbn':
            yu_shu_book.search_by_isbn(q)
        else:
            yu_shu_book.search_by_keyword(q, page)
        books.fill(yu_shu_book, q)
        return json.dumps(books, default=lambda o: o.__dict__)
    else:
        return jsonify(search_form.errors)
